/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.slice.fraction;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.ResourceHelper;
import com.lingeringdream.luciole.helper.list.PageProvider;
import com.lingeringdream.luciole.helper.list.TabListItemProvider;
import com.lingeringdream.luciole.model.Constants;
import com.lingeringdream.luciole.slice.ResultListSlice;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 主页面-识别fraction
 *
 * @author Kirky
 * @version 1.2
 * @date 2022/4/28
 */
public class ScanFraction extends Fraction {
    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x12, ScanFraction.class.getSimpleName());
    private final AbilitySlice slice;
    private Component scanFraction;
    private PageSlider slider;
    private TabList tabList;
    private DataAbilityHelper helper;
    private boolean isChinese;

    public ScanFraction(AbilitySlice slice) {
        this.slice = slice;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        scanFraction = scatter.parse(ResourceTable.Layout_fraction_scan, container, false);

        initSearchBar();
        initRecognise();
        initTabList();
        initIndicator();
        return scanFraction;
    }

    @Override
    protected void onActive() {
        super.onActive();
        isChinese = "zh".equals(Locale.getDefault().getLanguage());
    }

    /**
     * 初始化搜索栏
     */
    private void initSearchBar() {
        DependentLayout searchBar = scanFraction.findComponentById(ResourceTable.Id_fraction_scan_searchbar);
        Text title = scanFraction.findComponentById(ResourceTable.Id_searchBar_title);
        title.setText("请输入物品名称");
        searchBar.setClickedListener(component -> {
            Intent intent = new Intent();
            intent.setParam("isClassify", true);
            slice.present(new ResultListSlice(), intent);
        });
    }

    /**
     * 初始化识别按钮
     */
    private void initRecognise() {
        DirectionalLayout identification = scanFraction.findComponentById(ResourceTable.Id_fraction_scan_center_layout);

        identification.setClickedListener(component -> {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder().withDeviceId("")
                    .withBundleName(getBundleName())
                    .withAbilityName("com.lingeringdream.luciole.IdentityAbility")
                    .build();
            intent.setOperation(operation);
            slice.startAbility(intent);
        });
    }

    /**
     * 初始化tab
     */
    private void initTabList() {
        tabList = scanFraction.findComponentById(ResourceTable.Id_scan_tabList);
        TabList.Tab tab = tabList.new Tab(this);
        tab.setText(ResourceHelper.getString(this, ResourceTable.String_recyclable, "可回收垃圾", null));
        tabList.addTab(tab, 0, true);

        tab = tabList.new Tab(this);
        tab.setText(ResourceHelper.getString(this, ResourceTable.String_food, "厨余垃圾", null));
        tabList.addTab(tab);

        tab = tabList.new Tab(this);
        tab.setText(ResourceHelper.getString(this, ResourceTable.String_other, "其他垃圾", null));
        tabList.addTab(tab);

        tab = tabList.new Tab(this);
        tab.setText(ResourceHelper.getString(this, ResourceTable.String_harmful, "有害垃圾", null));
        tabList.addTab(tab);

        tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                // 当某个Tab从未选中状态变为选中状态时的回调
                int position = tab.getPosition();
                slider.setCurrentPage(position);
            }

            @Override
            public void onUnselected(TabList.Tab tab) {
                // 当某个Tab从选中状态变为未选中状态时的回调
            }

            @Override
            public void onReselected(TabList.Tab tab) {
                // 当某个Tab已处于选中状态，再次被点击时的状态回调
            }
        });
    }

    /**
     * 初始化list
     */
    private void initIndicator() {
        slider = scanFraction.findComponentById(ResourceTable.Id_scan_slider);
        PageProvider pageProvider = new PageProvider(slice, getData());
        slider.setProvider(pageProvider);


        slider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageSlideStateChanged(int i) {

            }

            @Override
            public void onPageChosen(int i) {
                tabList.selectTabAt(i);
            }
        });
    }

    /**
     * 获取TabList中的数据
     */
    private List<TabListItemProvider> getData() {
        List<TabListItemProvider> data = new ArrayList<>();
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        helper = DataAbilityHelper.creator(scanFraction.getContext());
        for (int i = 0; i < 4; ++i) {
            TabListItemProvider provider = new TabListItemProvider(slice,isChinese);
            predicates.clear();
            predicates.equalTo("class", i);
            predicates.limit(10);

            try {
                String[] columns = new String[]{"cname"};
                ResultSet resultSet = helper.query(Uri.parse(Constants.TABLE_CLASS.getValue()), columns, predicates);
                if (resultSet == null || resultSet.getRowCount() == 0) {
                    HiLog.info(TAG, "query: resultSet is null or no result found");
                    continue;
                }
                resultSet.goToFirstRow();
                while (resultSet.goToNextRow()) {
                    provider.addItem(resultSet.getString(resultSet.getColumnIndexForName("cname")));
                }

            } catch (Exception e) {
                HiLog.error(TAG, "query: " + e.getMessage());
            }

            data.add(provider);
        }
        helper.release();
        return data;
    }
}
